import {EventsEmit, EventsOff, EventsOn, EventsOnce} from "frontend/src/wailsjs/runtime";

export interface Response {
    Error: string
}

export interface SpeedOfProgress {
    Name: string
    Path: string
    Url: string
    Total: number
    Current: number
    Speed: string
}

export type ProgressListener = (data: SpeedOfProgress) => void

export function Download(url: string, path: string, progressListener?:ProgressListener) {
    return new Promise<null | Error>((resolve, reject) => {
        let downloadProgressChannel = `download:progress:${path}`
        EventsOn(downloadProgressChannel, (data:SpeedOfProgress) => {
            if(!progressListener){
                return
            } else {
                progressListener(data)
            }
        })

        EventsOnce(`download:done:${path}`, (data: Response) => {
            EventsOff(downloadProgressChannel)

            console.log(data)
            if (!data.Error) {
                resolve(null)
            } else {
                reject(new Error(data.Error))
            }
        })
        EventsEmit("download", url, path)
    })
}


(window as any).download = Download